package com.demo.task.ext

import com.google.gson.Gson
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.URL

private val gson by lazy { Gson() }
fun Any.toJson(): String {
    return  gson.toJson(this)
}

fun String.jsonFromUrl(): String? {
    return try {
        val url = URL(this)
        val connection = url.openConnection()
        connection.getInputStream().use {
            val stringBuilder = StringBuilder()
            BufferedReader(InputStreamReader(it)).use { reader ->
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    stringBuilder.append(line)
                }
            }
            stringBuilder.toString()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}